import React, {useState, useEffect} from 'react';
import {
    Breadcrumb,
    Button,
    Col,
    Form,
    Input,
    Layout,
    message,
    Modal,
    Popconfirm,
    Row, Select,
    Space
} from "antd";
import {Content} from "antd/es/layout/layout";
import {useNavigate} from "react-router-dom";
import {getAllUrlsByPage, getUrlDetailById, addUrl, updateUrlById, removeUrl} from '../../../api/list'
import Mytable from "../../../pages/Mytable";
import {iconList} from "../../../icons";

function Links(props) {
    const navigate = useNavigate()
    const [searchForm] = Form.useForm();
    const [urlForm] = Form.useForm();
    const [total, setTotal] = useState(0);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [parent, setParent] = useState(true);
    const [parentId, setParentId] = useState(0)
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [edit, setEdit] = useState(false);
    const [url, setUrl] = useState({
        "detail": "",
        "url": ""
    })
    const [page, setPage] = useState({
        "current": 1,
        "pageSize": 10
    })
    const pagination = {
        onShowSizeChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        onChange: (current, pageSize) => {
            paginationChange(current, pageSize)
        },
        showSizeChanger: true,
        total,
        current: page.current,
        pageSize: page.pageSize,
        defaultPageSize: 10,
        pageSizeOptions:
            [5, 10, 15, 20]
    }
    const paginationChange = async (current, pageSize) => {
        setPage({
            pageSize,
            current,
        })
    }
    const columns = [
        {
            title: '路径名称',
            width: '50vh',
            dataIndex: 'detail',
        },
        {
            title: '路径地址',
            dataIndex: 'url',
        },
        {
            title: '操作',
            dataIndex: 'repayment',
            render: (_, record) => (<Space>
                <Button type='primary' onClick={async () => {
                    const {data: res} = await getUrlDetailById(record.id)
                    setParent(res.data['parent_id'] === 0)
                    setEdit(true)
                    urlForm.setFieldsValue(res.data)
                    setIsModalVisible(true)
                }}>编辑路由</Button>
                <Button type='primary' onClick={async () => {
                    setParent(false)
                    setParentId(record.id)
                    setIsModalVisible(true)
                }} style={{display: record['parent_id'] === 0 ? 'block' : 'none'}}>添加子路路由</Button>
                <Popconfirm title="确认删除？" okText="确认" cancelText="取消" onConfirm={async () => {
                    const {data: res} = await removeUrl(record.id)
                    message.success(res.msg)
                    setPage({...page,current: 1})
                }}>
                    <Button type='danger'>删除</Button></Popconfirm>
            </Space>)
        }
    ];
    useEffect(() => {
        setLoading(true)
        getAllUrlsByPage({...page, ...url}).then(response => {
            const {records, total} = response.data.data
            setTotal(total)
            setData(records)
            setLoading(false)
        })
    }, [page, url])
    return (
        <Layout style={{padding: '0 24px 24px'}}>
            <Breadcrumb style={{margin: '16px 0'}}>
                <Breadcrumb.Item onClick={() => navigate("/main")}>首頁</Breadcrumb.Item>
                <Breadcrumb.Item>路由管理</Breadcrumb.Item>
            </Breadcrumb>
            <Content
                className="site-layout-background"
                style={{
                    padding: 24,
                    margin: 0,
                    minHeight: 280,
                }}
            >
                <Form
                    name="basic"
                    autoComplete="off"
                    form={searchForm}
                    style={{
                        marginBottom: '10px'
                    }}
                    onFinish={(values) => {
                        setUrl(values)
                        setPage({...page, current: 1})
                    }}
                >
                    <Row gutter={24}>
                        <Col span={8}><Form.Item
                            label="路径名称"
                            name='detail'
                        >
                            <Input/>
                        </Form.Item></Col>

                        <Col span={8}>
                            <Form.Item
                                label="路径地址"
                                name='url'
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                        <Col
                            span={8}
                            style={{
                                textAlign: 'right',
                            }}
                        >
                            <Space>
                                <Button type="primary" onClick={() => {
                                    setIsModalVisible(true)
                                }}>
                                    添加路由
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button
                                    onClick={async () => {
                                        searchForm.resetFields()
                                        const formValue = await searchForm.validateFields()
                                        setUrl(formValue)
                                        setPage({...page, current: 1})
                                    }}
                                >
                                    重置
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <Mytable
                    columns={columns}
                    dataSource={data}
                    pagination={pagination}
                    bordered
                    loading={loading}
                />
                <Modal title={edit ? '编辑路由' : '添加路由'} visible={isModalVisible} closable={false} footer={null}>
                    <Form
                        name="basic"
                        autoComplete="off"
                        layout={'vertical'}
                        form={urlForm}
                        onFinish={async (values) => {
                            if (edit) {
                                const {data: res} = await updateUrlById(values)
                                message.success(res.msg)
                            } else {
                                const {data:res} = await addUrl({...values, parent_id: parentId})
                                message.success(res.msg)
                            }
                            setIsModalVisible(false)
                            setParent(true)
                            setParentId(0)
                            setEdit(false)
                            urlForm.resetFields()
                            setPage({...page})
                        }}
                    >
                        <Form.Item
                            label="id"
                            name="id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="parent_id"
                            name="parent_id"
                            style={{display: 'none'}}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="路径名称"
                            name="detail"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入路径名称',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="路径地址"
                            name="url"
                            placeholder="请输入路径地址"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入路径地址',
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="图标名称"
                            name="icon"
                            placeholder="请输入图标名称"
                            rules={[
                                {
                                    required: parent,
                                    message: '请输入图标名称',
                                },
                            ]}
                            style={{
                                display: parent ? 'block' : "none"
                            }}
                        >
                            <Select
                                placeholder="选择是否自动提交"
                                allowClear
                            >
                                {iconList.map(icon => {
                                    return <Select.Option key={icon} value={icon}>{icon}</Select.Option>
                                })}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        ><Space>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button type="default" onClick={async () => {
                                setIsModalVisible(false)
                                urlForm.resetFields()
                                setParent(true)
                                setEdit(false)
                            }}>
                                取消
                            </Button>
                        </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
}

export default Links;